package com.pai4j.zwiki.controller;

import com.pai4j.zwiki.websocket.handler.ZWikiNotificationWebSocketHandler;
import com.pai4j.zwiki.websocket.service.ZWikiWebSocketService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket状态查询Controller
 * 
 * 提供WebSocket连接状态查询和管理接口
 *
 * @author pai4j
 * @since 2025-10-14
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/websocket")
@RequiredArgsConstructor
public class WebSocketStatusController {

    private final ZWikiWebSocketService webSocketService;

    private static final String CODE_SUCCESS = "0";
    private static final String CODE_ERROR = "500";

    /**
     * 查询WebSocket在线用户数
     */
    @GetMapping("/online-count")
    public ResponseEntity<Map<String, Object>> getOnlineCount() {
        try {
            int count = webSocketService.getOnlineUserCount();

            Map<String, Object> data = new HashMap<>();
            data.put("onlineCount", count);
            data.put("timestamp", System.currentTimeMillis());

            return buildSuccessResponse("查询成功", data);

        } catch (Exception e) {
            log.error("查询在线用户数失败", e);
            return buildErrorResponse("查询失败");
        }
    }

    /**
     * 查询指定用户是否在线
     */
    @GetMapping("/user-online/{userId}")
    public ResponseEntity<Map<String, Object>> isUserOnline(@PathVariable Long userId) {
        try {
            boolean online = webSocketService.isUserOnline(userId);

            Map<String, Object> data = new HashMap<>();
            data.put("userId", userId);
            data.put("online", online);
            data.put("timestamp", System.currentTimeMillis());

            return buildSuccessResponse("查询成功", data);

        } catch (Exception e) {
            log.error("查询用户在线状态失败: userId={}", userId, e);
            return buildErrorResponse("查询失败");
        }
    }

    /**
     * 发送测试消息（管理员接口）
     */
    @PostMapping("/test/send/{userId}")
    public ResponseEntity<Map<String, Object>> sendTestMessage(
            @PathVariable Long userId,
            @RequestParam String message) {
        try {
            Map<String, Object> testData = new HashMap<>();
            testData.put("type", "TEST");
            testData.put("message", message);
            testData.put("timestamp", System.currentTimeMillis());

            com.pai4j.common.util.JsonUtil jsonUtil = new com.pai4j.common.util.JsonUtil();
            String jsonMessage = jsonUtil.toJsonString(testData);

            boolean success = ZWikiNotificationWebSocketHandler.sendToUser(String.valueOf(userId), jsonMessage);

            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            result.put("message", success ? "发送成功" : "用户不在线或发送失败");

            return buildSuccessResponse("操作完成", result);

        } catch (Exception e) {
            log.error("发送测试消息失败: userId={}", userId, e);
            return buildErrorResponse("发送失败");
        }
    }

    /**
     * 广播系统通知（管理员接口）
     */
    @PostMapping("/broadcast")
    public ResponseEntity<Map<String, Object>> broadcastNotification(
            @RequestParam String title,
            @RequestParam String message) {
        try {
            webSocketService.broadcastSystemNotification(title, message);

            Map<String, Object> result = new HashMap<>();
            result.put("onlineCount", webSocketService.getOnlineUserCount());
            result.put("message", "广播成功");

            return buildSuccessResponse("广播完成", result);

        } catch (Exception e) {
            log.error("广播系统通知失败", e);
            return buildErrorResponse("广播失败");
        }
    }

    // ========== 辅助方法 ==========

    private ResponseEntity<Map<String, Object>> buildSuccessResponse(String message, Object data) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", CODE_SUCCESS);
        result.put("message", message);
        result.put("data", data);
        return ResponseEntity.ok(result);
    }

    private ResponseEntity<Map<String, Object>> buildErrorResponse(String message) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", CODE_ERROR);
        result.put("message", message);
        return ResponseEntity.internalServerError().body(result);
    }
}

